<template>
  <div class="create">
    <!-- 头部 -->
    <myheader></myheader>
    <h3>新建文章</h3>
    <!-- 图片上传 -->
    <el-upload
      class="avatar-uploader"
      action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>

    <!--富文本 /文章详情  -->
    <el-form
      class="form"
      :model="form"
      label-width="120px"
      label-position="top"
    >
      <el-form-item label="文章标题:">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="文章详情:">
          <div style="border: 1px solid #ccc; margin-top: 10px">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
              style="border-bottom: 1px solid #ccc"
            />
            <Editor
              :defaultConfig="editorConfig"
              :mode="mode"
              v-model="valueHtml"
              style="height: 400px; overflow-y: hidden"
              @onCreated="handleCreated"
              @onChange="handleChange"
              @onDestroyed="handleDestroyed"
              @onFocus="handleFocus"
              @onBlur="handleBlur"
              @customAlert="customAlert"
              @customPaste="customPaste"
            />
          </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">发表文章</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
// 头部
import myheader from '@/components/MyHeader'
// 富文本
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { upload ,Createanewarticle} from "@/utils/api";
import { ref, reactive, onBeforeUnmount, shallowRef, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import {useStore} from 'vuex'
import {useRouter} from 'vue-router'
const {push} = useRouter()
const {state} = useStore();
const imageUrl = ref("");
const form = reactive({
  title: "",
  content: "",
  image:'',
  column:'',  //专栏id
  author:'', //图片id
})
const mode ='default'
//发表文章事件
const onSubmit = () => {
  form.column =state.column
  form.author = state.author

  Createanewarticle(form).then(res =>{
    push({path:'/zhuanlan',
    query:{ id:state.column}
    })
  })
   
};
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile: any
) => {
  if (uploadFile) {
    let fromdata = new FormData();
    fromdata.append("file", uploadFile.raw);
    upload(fromdata).then((res) => {
      form.image =res.data._id
      // form.author =res.data._id

    });
  }
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
};

const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
const editorRef = shallowRef();

    const valueHtml = ref('');

    onMounted(() => {
      setTimeout(() => {
        valueHtml.value = '';
      }, 1500);
    });

    const toolbarConfig = {};
    const editorConfig = { placeholder: '请输入内容...' };

    // 组件销毁时，也及时销毁编辑器，重要！
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.destroy();
    });

    // 编辑器回调函数
    const handleCreated = (editor:any) => {
      console.log('created', editor);
      editorRef.value = editor; // 记录 editor 实例，重要！
    };
    const handleChange = (editor:any) => {
      let a  = editor.getHtml().slice(3,-4)
      form.content =a
    };
    const handleDestroyed = (editor:any) => {
      console.log('destroyed', editor);
    };
    const handleFocus = (editor:any) => {
      console.log('focus', editor);
    };
    const handleBlur = (editor:any) => {
      console.log('blur', editor);
    };
    const customAlert = (info:any, type:any) => {
      alert(`【自定义提示】${type} - ${info}`);
    };
    const customPaste = (editor:any, event:any, callback:any) => {
      console.log('ClipboardEvent 粘贴事件对象', event);

      // 自定义插入内容
      editor.insertText('xxx');

      // 返回值（注意，vue 事件的返回值，不能用 return）
      callback(false); // 返回 false ，阻止默认粘贴行为
      // callback(true) // 返回 true ，继续默认的粘贴行为
    };

    const insertText = () => {
      const editor = editorRef.value;
      if (editor == null) return;

      editor.insertText('hello world');
    };

    const printHtml = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      console.log(editor.getHtml());
    };

    const disable = () => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.disable()
    };
</script>

<style lang="scss" scoped>
.form {
  margin-top: 20px;
}
.create {
  width: 800px;
  margin: 0 auto;
  h3 {
    margin: 10px 0;
  }
}
.avatar-uploader {
  width: 100%;
  height: 250px;
  background-color: #ccc;
  text-align: center;
  .avatar-uploader-icon {
    width: 200px;
    height: 200px;
    font-size: 50px;
  }
  .avatar {
    margin: 25px 0;
    width: 200px;
    height: 200px;
  }
}
</style>